package com.kll.tv.views

import android.view.Gravity
import android.view.View
import com.bumptech.glide.Glide
import com.google.i18n.phonenumbers.PhoneNumberUtil
import com.kll.carolinehmibiz.OperationManager
import com.kll.carolinehmibiz.model.AccountModel
import com.kll.carolinehmibiz.model.OperateListener
import com.kll.carolinehmibiz.net.bean.GetFamilyResponse
import com.kll.carolinehmibiz.net.bean.RefreshTokenResponse
import com.kll.carolinehmibiz.presentation.listener.NewContactProtocol
import com.kll.carolinehmibiz.presentation.presenter.NewContactPresenter
import com.kll.tv.R
import com.kll.tv.base.views.BaseActivity
import com.kll.tv.databinding.ActivityNewContactBinding
import com.kll.tv.utils.AppToast
import com.kll.tv.utils.GlideEngine
import com.kll.carolinehmibiz.base.utils.L
import com.kll.tv.utils.PopWindow
import com.kll.tv.views.adapter.PersonalAvatarPopAdapter
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import com.tencent.qcloud.tuicore.util.SoftKeyBoardUtil
import java.io.File

/**
 * 新建联系人 or 编辑联系人
 */
class NewContactActivity: BaseActivity<NewContactPresenter>(), NewContactProtocol.IView {
    private lateinit var binding: ActivityNewContactBinding
    private var mobile = ""
    private var avatar = "http://www.baidu.com"
    private var firstName = ""
    private var lastName = ""
    private var remark = ""
    private var data: GetFamilyResponse? = null
    private var isFrom = 0 // 0-新建 1-编辑
    private var popAvatarWindow: PopWindow? = null
    private var personalAvatarPopAdapter: PersonalAvatarPopAdapter? = null

    override fun initViewBinding(): View {
        binding = ActivityNewContactBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun createPresenter(): NewContactPresenter {
        return NewContactPresenter(this, this)
    }

    override fun init() {
        isFrom = intent.getIntExtra("isFrom", 0)

        if (isFrom == 1) {
            data = intent.getBundleExtra("data")!!.getSerializable("data") as GetFamilyResponse
            if (data != null) {
                binding.tvTitle.text = "编辑联系人"
                binding.edtFirstName.setText(data!!.first_name)
                binding.edtLastName.setText(data!!.last_name)
                binding.edtMobile.setText(data!!.mobile)
                binding.edtRemarks.setText(data!!.remark)
                if (data!!.avatar != "") {
                    Glide.with(this).load("http://" + data!!.avatar).into(binding.ivHead)
                }
                binding.tvDelete.visibility = View.VISIBLE
            }
        } else {
            binding.tvDelete.visibility = View.GONE
        }

        initListener()
    }

    private fun initListener() {
        binding.tvCancel.setOnClickListener {
            finish()
        }
        binding.tvOk.setOnClickListener {
            if (isFrom == 1) {
                // 编辑联系人
                mobile = binding.edtMobile.text.toString().trim()
                firstName = binding.edtFirstName.text.toString().trim()
                lastName = binding.edtLastName.text.toString().trim()
                remark = binding.edtRemarks.text.toString().trim()

                var isValidate = false
                if (mobile.length > 8) {
                    // 校验手机号码
                    isValidate = try {
                        PhoneNumberUtil.getInstance()
                            .isValidNumber(PhoneNumberUtil.getInstance().parse(mobile, "CN"))
                    } catch (e: Exception) {
                        return@setOnClickListener
                    }
                }
                if (!isValidate) {
                    AppToast.show("请输入正确的手机号码！", 2000)
                    return@setOnClickListener
                }

                mPresenter.editFamily(data!!.id, mobile, avatar, firstName, lastName, remark)
            } else {
                // 新建联系人
                mobile = binding.edtMobile.text.toString().trim()
                firstName = binding.edtFirstName.text.toString().trim()
                lastName = binding.edtLastName.text.toString().trim()
                remark = binding.edtRemarks.text.toString().trim()

                var isValidate = false
                if (mobile.length > 8) {
                    // 校验手机号码
                    isValidate = try {
                        PhoneNumberUtil.getInstance()
                            .isValidNumber(PhoneNumberUtil.getInstance().parse(mobile, "CN"))
                    } catch (e: Exception) {
                        return@setOnClickListener
                    }
                }
                if (!isValidate) {
                    AppToast.show("请输入正确的手机号码！", 2000)
                    return@setOnClickListener
                }

                mPresenter.addFamily(mobile, avatar, firstName, lastName, remark)
            }
        }
        // 删除联系人
        binding.tvDelete.setOnClickListener {
            mPresenter.delFamily(data!!.id)
        }
        // 点击头像
        binding.ivHead.setOnClickListener {
            toShowAvatarPop()
        }

        binding.edtFirstName.setOnFocusChangeListener(object : View.OnFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (!hasFocus) {
                    SoftKeyBoardUtil.hideKeyBoard(binding.edtFirstName.windowToken)
                } else {
                    SoftKeyBoardUtil.showSoftInput(binding.edtFirstName)
                }
            }

        })
        binding.edtLastName.setOnFocusChangeListener(object : View.OnFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (!hasFocus) {
                    SoftKeyBoardUtil.hideKeyBoard(binding.edtLastName.windowToken)
                } else {
                    SoftKeyBoardUtil.showSoftInput(binding.edtLastName)
                }
            }

        })
        binding.edtMobile.setOnFocusChangeListener(object : View.OnFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (!hasFocus) {
                    SoftKeyBoardUtil.hideKeyBoard(binding.edtMobile.windowToken)
                } else {
                    SoftKeyBoardUtil.showSoftInput(binding.edtMobile)
                }
            }

        })
        binding.edtRemarks.setOnFocusChangeListener(object : View.OnFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (!hasFocus) {
                    SoftKeyBoardUtil.hideKeyBoard(binding.edtRemarks.windowToken)
                } else {
                    SoftKeyBoardUtil.showSoftInput(binding.edtRemarks)
                }
            }

        })
    }

    // 弹窗
    private var toShowAvatarPopIsBusying = false
    private fun toShowAvatarPop() {
        if (toShowAvatarPopIsBusying) return
        toShowAvatarPopIsBusying = true

        if (popAvatarWindow == null) {
            popAvatarWindow = PopWindow(this)
            personalAvatarPopAdapter = PersonalAvatarPopAdapter(this,
                View.OnClickListener { v ->
                    when(v.id) {
                        R.id.tv_photograph -> {
                            // 拍照
                            AppToast.show("拍摄", 2000)
                            getAndroidQCamera()
                        }
                        R.id.tv_from -> {
                            // 从电视选择
                            AppToast.show("从相册选择", 2000)
                            getAndroidQImage()
                        }
                        R.id.tv_cancel -> {
                            // 取消
                            AppToast.show("取消", 2000)
                        }
                    }
                    popAvatarWindow!!.dismiss()
                })
            popAvatarWindow!!.addView(personalAvatarPopAdapter)
            popAvatarWindow!!.animationStyle = R.style.popwindow_anim_style
        }
        popAvatarWindow!!.showAtLocation(binding.root, Gravity.BOTTOM, 0, 0)
        toShowAvatarPopIsBusying = false
    }

    /**
     * 适配AndroidQ的相册获取
     */
    private fun getAndroidQImage() {
        PictureSelector.create(this)
            .openGallery(PictureMimeType.ofImage()) // 全部-ofAll 图片-ofImage 视频-ofVideo 音频-ofAudio
            .loadImageEngine(GlideEngine.createGlideEngine())
            .isWeChatStyle(true)
            .maxSelectNum(1) // 最大图片选择数量
            .minSelectNum(1) // 最小图片选择数量
            .compress(false)
            .minimumCompressSize(1024)
            .imageSpanCount(4) // 每行显示个数
            .isReturnEmpty(false) // 未选择数据时点击按钮是否可以返回
            .enableCrop(true) // 是否裁剪
            .withAspectRatio(1, 1) // 裁剪比例，如16:9 3:2 3:4 1:1 可自定义
            .showCropFrame(true) // 是否显示裁剪矩形边框，圆形裁剪时建议设为 false
            .showCropGrid(true) // 是否显示裁剪矩形网格，圆形裁剪时建议设为false
            .selectionMode(PictureConfig.MULTIPLE) // 多选 or 单选
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: MutableList<LocalMedia>?) {
                    if (result != null && result.size > 0) {
                        L.d("TAG", "cutPath: ${File(result[0].cutPath)}")
                        mPresenter.uploadHeadImg(File(result[0].cutPath))
                    }
                }

                override fun onCancel() {
                    AppToast.show("操作已取消！", 2000)
                }

            })
    }

    /**
     * 拍照
     */
    private fun getAndroidQCamera() {
        PictureSelector.create(this)
            .openCamera(PictureMimeType.ofImage())
            .loadImageEngine(GlideEngine.createGlideEngine())
            .enableCrop(true) // 是否裁剪
            .withAspectRatio(1, 1) // 裁剪比例，如16:9 3:2 3:4 1:1 可自定义
            .showCropFrame(true) // 是否显示裁剪矩形边框，圆形裁剪时建议设为 false
            .showCropGrid(true) // 是否显示裁剪矩形网格，圆形裁剪时建议设为false
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: MutableList<LocalMedia>?) {
                    if (result != null && result.size != 0) {
                        L.d("TAG", "cutPath: ${File(result[0].cutPath)}")
                        mPresenter.uploadHeadImg(File(result[0].cutPath))
                    }
                }

                override fun onCancel() {
                    AppToast.show("操作已取消！", 2000)
                }

            })
    }

    override fun addFamilySuccessed() {
        AppToast.show("添加成功！", 2000)
        setResult(1)
        finish()
    }

    override fun addFamilyFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(data.token)
                    mPresenter.addFamily(mobile, avatar, firstName, lastName, remark)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    override fun editFamilySuccessed() {
        AppToast.show("编辑成功！", 2000)
        setResult(2)
        finish()
    }

    override fun editFamilyFailed(code: Int, message: String) {
        AppToast.show(message,2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var datas = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(datas.token)
                    mPresenter.editFamily(data!!.id, mobile, avatar, firstName, lastName, remark)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    override fun delFamilySuccessed() {
        AppToast.show("删除成功！", 2000)
        setResult(3)
        finish()
    }

    override fun delFamilyFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var datas = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(datas.token)
                    mPresenter.delFamily(data!!.id)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }


    /**
     * 上传头像成功
     */
    override fun uploadHeadImgSuccessed(path: String) {
        AppToast.show("上传头像成功！", 2000)
        avatar = path
        Glide.with(this).load("http://" + avatar).into(binding.ivHead)
    }

    /**
     * 上传头像失败
     */
    override fun uploadHeadImgFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(data.token)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

}